<?php
/**
 * @file user.php $
 * @author LiangJian (liangjian@haibao.com) $
 * @date 2015年7月22日 下午12:09:25 $
 * @brief  $
 */
namespace haibao\app\data;

use haibao\api\Config;

class Authuser extends \haibao\app\data\Base{

    public function __construct(){
        parent::__construct('\haibao\app\model\data\Authuser');
        $this->setConfig( \haibao\classlibrary\app\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_DZ3 );
    }

    public function getUserById($userId){
        return $this->getOneById($userId);
    }
    
    public function getUserAvatarMd5($userId){
    	$cache = new \haibao\app\cache\User();
    	$cachePhotoMd5 = $cache->getUserPhotoMd5($userId);
    	if(empty($cachePhotoMd5)){
    		$cachePhotoMd5 = '';
    		$userInfo = $this->getUserById($userId);
    		if(!empty($userInfo) && !empty($userInfo->avatar_md5)){
    			$cachePhotoMd5 = $userInfo->avatar_md5;
    			$cache->setUserPhotoMd5($userId, $cachePhotoMd5);
    		}
    	}
    	
    	return $cachePhotoMd5;
    }
    
    public function getUserByMobile($mobile){
        $sql = 'select id,nickname,username,password,email,mobile,is_active,avatar_md5 from `auth_user` where mobile=%s limit 1';
        $result = $this->query($sql, array(
            $mobile
        ));
        return $result->fetch_assoc();
    }
    
    public function getUserByNickname($nickname){
        $sql = "select id,nickname,username,password,email,mobile,is_active,avatar_md5 from `auth_user` where nickname=%s limit 1";
        $result = $this->query($sql, array(
            $nickname
        ));
        return $result->fetch_assoc();
    }
    
    public function getUserByUsername($username){
        $sql = "select id,nickname,username,password,email,mobile,is_active,avatar_md5 from `auth_user` where username=%s limit 1";
        $result = $this->query($sql, array(
            $username
        ));
        return $result->fetch_assoc();
    }
	
	public function getUserByEmail($email){
		$sql = "select id,nickname,username,password,email,mobile,is_active,avatar_md5 from `auth_user` where email=%s limit 1";
		$result = $this->query($sql, array(
				$email
		));
		return $result->fetch_assoc();
	}
    
    public function getUserByHBUser($username,$mobile){
        $sql = "select id,username,password,email,mobile,is_active from `auth_user` where username=%s or mobile=%s limit 1";
        $result = $this->query($sql, array(
            $username, $mobile
        ));
        return $result->fetch_assoc();
    }
    
    public function getNicknameByUserIdArr(array $userIdArr){
        if(!$userIdArr){
            return false;
        }
        $str = preg_replace('/(\d+)/', '%s', implode(',', $userIdArr));
        $result = $this->query('select Id,Nickname from auth_user where Id in('.$str.')', $userIdArr);
        $retArr = array();
        while($result->fetch_assoc()){
            $retArr[$result->getData('Id')] = $result->getData('Nickname');
        }
        return $retArr;
    }
    
    /**
     * 记录用户登录历史记录
     */
    public function recordLogin($userId,$system,$source = \haibao\app\model\data\UserLoginHistory::USER_TYPE_APP,$actionType = \haibao\app\model\data\UserLoginHistory::USER_ACTIONTYPE_LOGIN){
        $this->setConfig( \haibao\classlibrary\app\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_APP );
        $model = new \haibao\app\model\data\UserLoginHistory();
        $this->setTableName($model);
        $this->createUserLoginHistoryTable($model->getTableName());
        
        $this->query('insert into '.$model->getTableName().'(UserId,CreateTime,Source,SysType,ActionType) values(%s,%s,'.$this->escape($source).','.$this->escape($system).','.$this->escape($actionType).')', array(
            $userId, (new \DateTime())
        ));
        $this->setConfig( \haibao\classlibrary\app\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_DZ3 );
    }
    
    public function setUserAuater($userId,$avatar){
    	$this->beginTranscation();
        try {
            $this->query("update sns_myprofile set avatar=%s where user_id=%s limit 1", array($avatar, $userId));
            
            $avatar_md5 = md5($avatar);
            $this->query("update auth_user set avatar_md5=%s where id=%s limit 1", array($avatar_md5, $userId));
            
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }
        $this->endTranscation();
    }
    
    /**
     * 修改用户头像、性别、昵称
     */
    public function setUserInfo($userId, $userInfo){
        $this->beginTranscation();
        try {
            $this->query("update sns_myprofile set avatar=%s,gender=%s where user_id=%s limit 1", array(
                $userInfo['avatar'], $userInfo['sex'], $userId
            ));
            
            $this->query("update auth_user set nickname=%s,avatar_md5=%s where id=%s limit 1", array(
                $userInfo['nickname'], $userInfo['avatar_md5'], $userId
            ));
            
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }
        $this->endTranscation();
        
//         $this->setCommentUserNickName($userId, $userInfo['nickname']);
    }
	
	/**
	 * 保存用户信息
	 * @param \haibao\app\model\data\authuser $model
	 */
	public function saveUser($model, $type = null, $thirdId = null, $avator = null, $gender = \haibao\app\model\data\SnsMyProfile::GENDER_FEMALE){
		$this->beginTranscation();
		try {
			$this->add($model);
			
			$hbName = '报友'.$model->Id;
			if(!empty($model->mobile)){
			    $upData['nickname'] = $upData['username'] = $hbName;
			    $model->username = $hbName;
			}else{
			    $upData['nickname'] = $model->username;
			}
			$this->updateById($model->Id, $upData);
			
			// 保存第三方登录帐号
			if($model->Id > 0 && $type && $thirdId){
				$this->addBind($type, $model->Id, $thirdId);
			}
			
			if($model->Id > 0){
				$profileModel = new \haibao\app\model\data\SnsMyProfile();
				$profileModel->user_id = $model->Id;
				$profileModel->avatar = $avator;
				$profileModel->username = $model->username;
				$profileModel->gender = $gender;
				$profileModel->last_online = new \DateTime();
				$profileModel->is_email_verified = \haibao\app\model\data\SnsMyProfile::EMAIL_VERIFIED_NO;
				$profileModel->is_mobile_verified = !empty($model->mobile) ? \haibao\app\model\data\SnsMyProfile::MOBILE_VERIFIED_YES : \haibao\app\model\data\SnsMyProfile::MOBILE_VERIFIED_NO;
				
				$data = new \haibao\app\data\SnsMyProfile();
				$data->addSnsProfile($profileModel);
				
				$this->addUcenterData($model);
			}
			
			//添加用户查看消息日志
			$data = new \haibao\app\data\Account();
			$data->addUserMessageLog($model->Id);
			
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}

	private function setCommentUserNickName($userId,$nickName){
		$this->setConfig( \haibao\classlibrary\app\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_APP );
		$this->query("update Comment set Nickname=%s where UserId=%s", array(
				$nickName,$userId
		));
		$this->query("update CommentReply set FromNickname=%s where FromUserId=%s", array(
				$nickName,$userId
		));
		$this->query("update CommentReply set ToNickname=%s where ToUserId=%s", array(
				$nickName,$userId
		));
		$this->query("update CommentReply set ReceiveNickname=%s where ReceiveUserId=%s", array(
				$nickName,$userId
		));
	}
	
	
	/**
	 * 添加绑定的第三方用户ID
	 */
	private function addBind($type, $userId, $thirdId){
		$model = new \haibao\app\model\data\SnsWeiboBind();
		$model->user_id = $userId;
		if($type == \haibao\app\model\data\SnsWeiboBind::LOGIN_QQ){
			$model->qquid = $thirdId;
		}elseif($type == \haibao\app\model\data\SnsWeiboBind::LOGIN_WB){
			$model->wbuid = $thirdId;
		}elseif($type == \haibao\app\model\data\SnsWeiboBind::LOGIN_WX){
			$model->wxuid = $thirdId;
		}
		
		$data = new \haibao\app\data\SnsWeiboBind();
		$data->addBind($model);
	}

	/**
	 * 重置数据库中的密码
	 */
	public function resetPassword($userId, $password, $token = null){
	    $this->beginTranscation();
	    try {
	        $sql = 'update auth_user set password=%s where id=%s limit 1';
	        $this->query($sql, array(
	            $password, $userId
	        ));
	        	
	        $sql = 'update hb_ucenter_members set password=%s where uid=%s limit 1';
	        $this->query($sql, array(
	            $password, $userId
	        ));
	        
	        if($token){
	            $data = new \haibao\app\cache\User();
	            $data->deleteToken($token);
	        }
	    } catch (\Exception $e) {
	        $this->rollback();
	        throw $e;
	    }
	    $this->endTranscation();
	}
	
	/**
	 * 走数据库方式发送邮件
	 */
	public function sendMail($subject, $content, $mailto, $from){
		$this->setConfig( \haibao\classlibrary\app\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_DZ3 );
		$sql = 'insert into z_email_queue(`fromname`, `mailto`, `subject`, `content`, `contenttype`, `addtime`) values(%s,%s,%s,%s,%s,%s)';
		$this->query($sql, array(
			$from, $mailto, $subject, $content, 1, date('Y-m-d H:i:s'),
		));
	}

	/**
	 * 根据token获取用户ID
	 */
	public function getUserIdByToken($token){
	    $cache = new \haibao\app\cache\User();
	    return $cache->getUserByToken($token);
	}
	
	/**
	 * 根据用户ID获取邮箱手机找回密码的激活码（默认保留3天）
	 */
	public function getToken($userId){
		$token = time().'_'.$userId.'_'.rand(1000, 10000);
		$token = sha1($token);
	
		$cache = new \haibao\app\cache\User();
		$cache->setToken($token, $userId);
		return $token;
	}
	
	/**
	 * 获取手机验证码
	 */
	public function getSmsCaptcha($mobile){
	    $cache = new \haibao\app\cache\User();
	    $code = $this->generateCode();
	    $cache->setSmsCaptcha($mobile, $code, 60*10);
	
	    return $code;
	}
	
	/**
	 * 发送手机短信验证码次数加1
	 */
	public function setSendCount($mobile){
	    $cache = new \haibao\app\cache\User();
	    $cache->setSmsSendCount($mobile);
	}
	
	/**
	 * 获取某手机发送验证码次数
	 */
	public function getSendCount($mobile){
	    $cache = new \haibao\app\cache\User();
	    return $cache->getSmsSendCount($mobile);
	}
	
	/**
	 * 生成6位随机数字
	 */
	private function generateCode($length = 6){
	    return rand(pow(10,($length-1)), pow(10,$length)-1);
	}

	/**
	 * 更新用户最后登录时间
	 */
	public function updateLastLoginTime($userId){
	    $this->updateById($userId, array(
	        \haibao\app\model\filter\AuthUser::CONDITION_FIELD_LAST_LOGIN => new \DateTime()
	    ));
	    	
	    $sql = 'update sns_myprofile set last_online=%s where user_id=%s limit 1';
	    $this->query($sql, array(
	        date('Y-m-d H:i:s'), $userId
	    ));
	}
	
	/**
	 * 添加ucenter注册用户初始信息
	 *
	 * @param \haibao\app\model\data\authuser $model
	 */
	private function addUcenterData($model){
	    $user_id = $model->Id;
	    $name = $model->username;
	    $password = $model->password;
	    $email = $model->email ? $model->email : '';
	
	    $emailstatus = 1;
	    $avatarstatus= 0;
	    $timenow = time();
	
	    $sql = 'replace into hb_ucenter_members(uid,username,`password`,email,regdate) values(%s,%s,%s,%s,%s)';
	    $this->query($sql, array(
	        $user_id, $name, $password, $email, $timenow
	    ));
	
	    $sql = 'replace into hb_common_member(uid,email,username,`password`,groupid,emailstatus,avatarstatus,regdate,credits) values(%s,%s,%s,%s,%s,%s,%s,%s,%s)';
	    $this->query($sql, array(
	        $user_id, $email, $name, $password, '11', $emailstatus, $avatarstatus, $timenow, '0',
	    ));
	
	    $sql = 'replace into hb_common_member_count(uid,extcredits1,extcredits2) values(%s,%s,%s)';
	    $this->query($sql, array(
	        $user_id, '0', '0',
	    ));
	
	    $sql = 'replace into hb_common_member_status(uid) values(%s)';
	    $this->query($sql, array(
	        $user_id
	    ));
	
	    $sql ='replace into hb_common_member_profile(uid) values(%s)';
	    $this->query($sql, array($user_id));
	
	    $blockpostion=addslashes('a:3:{s:5:"block";a:1:{s:12:"frame`frame1";a:3:{s:4:"attr";a:4:{s:4:"name";s:6:"frame1";s:8:"moveable";s:5:"false";s:9:"className";s:8:"frame cl";s:6:"titles";s:0:"";}s:18:"column`frame1_left";a:3:{s:4:"attr";a:2:{s:4:"name";s:11:"frame1_left";s:9:"className";s:8:"z column";}s:13:"block`profile";a:1:{s:4:"attr";a:3:{s:4:"name";s:7:"profile";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:6:"头像";s:4:"href";s:63:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=profile";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:13:"block`visitor";a:1:{s:4:"attr";a:3:{s:4:"name";s:7:"visitor";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:12:"最近访客";s:4:"href";s:75:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=friend&view=visitor";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}}s:20:"column`frame1_center";a:10:{s:4:"attr";a:2:{s:4:"name";s:13:"frame1_center";s:9:"className";s:8:"z column";}s:11:"block`album";a:1:{s:4:"attr";a:3:{s:4:"name";s:5:"album";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:6:"相册";s:4:"href";s:80:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=album&view=me&from=space";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:12:"block`block3";a:1:{s:4:"attr";a:3:{s:4:"name";s:6:"block3";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:12:"迷你博客";s:4:"href";s:0:"";s:5:"color";s:0:"";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:10:"block`feed";a:1:{s:4:"attr";a:3:{s:4:"name";s:4:"feed";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:12:"小道消息";s:4:"href";s:79:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=home&view=me&from=space";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:10:"block`blog";a:1:{s:4:"attr";a:3:{s:4:"name";s:4:"blog";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:6:"日志";s:4:"href";s:79:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=blog&view=me&from=space";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:12:"block`block1";a:1:{s:4:"attr";a:3:{s:4:"name";s:6:"block1";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:18:"我喜欢的明星";s:4:"href";s:0:"";s:5:"color";s:0:"";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:12:"block`block2";a:1:{s:4:"attr";a:3:{s:4:"name";s:6:"block2";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:18:"我喜欢的品牌";s:4:"href";s:0:"";s:5:"color";s:0:"";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:12:"block`thread";a:1:{s:4:"attr";a:3:{s:4:"name";s:6:"thread";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:12:"最新帖子";s:4:"href";s:81:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=thread&view=me&from=space";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:12:"block`friend";a:1:{s:4:"attr";a:3:{s:4:"name";s:6:"friend";s:9:"className";s:15:"block move-span";s:6:"titles";a:3:{i:0;a:8:{s:4:"text";s:15:"我的好盆友";s:4:"href";s:81:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=friend&view=me&from=space";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}s:10:"block`wall";a:1:{s:4:"attr";a:3:{s:4:"name";s:4:"wall";s:9:"className";s:15:"block move-span";s:6:"titles";a:4:{i:0;a:8:{s:4:"text";s:9:"留言板";s:4:"href";s:60:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=wall";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:0:"";s:3:"src";s:0:"";}i:1;a:8:{s:4:"text";s:6:"全部";s:4:"href";s:60:"http://bbs.haibao.com/home.php?mod=space&uid=1170642&do=wall";s:5:"color";s:11:" !important";s:5:"float";s:0:"";s:6:"margin";s:0:"";s:9:"font-size";s:0:"";s:9:"className";s:5:"y xw0";s:3:"src";s:0:"";}s:9:"className";a:1:{i:0;s:16:"blocktitle title";}s:5:"style";s:0:"";}}}}}}s:13:"currentlayout";s:3:"1:3";s:10:"parameters";a:9:{s:6:"friend";a:2:{s:5:"title";s:15:"我的好盆友";s:7:"shownum";i:10;}s:5:"music";a:3:{s:7:"mp3list";a:2:{i:0;a:3:{s:6:"mp3url";s:43:"http://stream15.qqmusic.qq.com/35036372.mp3";s:7:"mp3name";s:15:"爸爸去哪儿";s:4:"cdbj";s:0:"";}i:1;a:3:{s:6:"mp3url";s:43:"http://stream13.qqmusic.qq.com/30815558.mp3";s:7:"mp3name";s:13:"I Remember Me";s:4:"cdbj";s:0:"";}}s:6:"config";a:8:{s:7:"showmod";s:7:"default";s:7:"autorun";s:4:"true";s:7:"shuffle";s:4:"true";s:12:"crontabcolor";s:7:"#D2FF8C";s:11:"buttoncolor";s:7:"#1F43FF";s:9:"fontcolor";s:7:"#1F43FF";s:9:"crontabbj";s:0:"";s:6:"height";i:100;}s:5:"title";s:9:"音乐盒";}s:6:"block1";a:2:{s:5:"title";s:18:"我喜欢的明星";s:7:"content";s:0:"";}s:6:"block2";a:2:{s:5:"title";s:18:"我喜欢的品牌";s:7:"content";s:0:"";}s:4:"feed";a:2:{s:5:"title";s:12:"小道消息";s:7:"shownum";i:10;}s:6:"block3";a:2:{s:5:"title";s:12:"迷你博客";s:7:"content";s:0:"";}s:6:"block4";a:2:{s:5:"title";s:18:"迷你博客广播";s:7:"content";s:0:"";}s:6:"block5";a:2:{s:5:"title";s:12:"最新帖子";s:7:"content";s:0:"";}s:4:"blog";a:3:{s:5:"title";s:6:"日志";s:7:"shownum";i:6;s:11:"showmessage";i:150;}}}');
	    $sql = 'replace into hb_common_member_field_home(uid,blockposition) values(%s,%s)';
	    $this->query($sql, array(
	        $user_id, $blockpostion
	    ));
	
	    $sql = 'replace into hb_common_member_field_forum(uid,customshow,groupterms) values(%s,%s,%s)';
	    $this->query($sql, array(
	        $user_id, '26', 'a:0:{}'
	    ));
	}
	
	/**
	 * 记录登录日志
	 */
	public function addLoginLog($userId, $username){
	    $sql = "insert into hb_zj_login_log_byx(`uid`,`username`,`logintime`) values(%s,%s,%s)";
	    $this->query($sql, array(
	        $userId, $username, date('Y-m-d H:i:s')
	    ));
	}
    
}